<template>
  <aside class="sidebar" :class="{ collapsed }">
    <div class="logo-bar" :class="{ 'logo-bar-collapsed': collapsed }">
      <div class="logo" v-if="!collapsed">知学岛</div>
      <button class="collapse-btn" @click="toggleCollapse">
        <svg v-if="!collapsed" width="32" height="32" viewBox="0 0 40 40" fill="none">
          <circle cx="20" cy="20" r="18" fill="#e5e5e5" stroke="#393e4a" stroke-width="2"/>
          <polyline points="23,13 16,20 23,27" fill="none" stroke="#393e4a" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        <svg v-else width="32" height="32" viewBox="0 0 40 40" fill="none">
          <circle cx="20" cy="20" r="18" fill="#e5e5e5" stroke="#393e4a" stroke-width="2"/>
          <polyline points="17,13 24,20 17,27" fill="none" stroke="#393e4a" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </button>
    </div>
    <template v-if="!collapsed">
      <el-button type="primary" :icon="Plus" class="new-chat-btn large-btn" size="small" @click="newChat">新建对话</el-button>
      <div class="sidebar-divider"></div>
      <div class="sidebar-section-title">最近对话</div>
      <div v-if="!userStore.userInfo" class="sidebar-login-tip">
        登录后可以保存问答记录
      </div>
      <div class="chat-list">
        <div
          v-for="chat in chatList"
          :key="chat.sessionId"
          :class="['chat-item', { active: chat.sessionId === activeChatId } ]"
          @click="selectChat(chat.sessionId)"
          style="display: flex; align-items: center; justify-content: space-between;"
        >
          <div style="flex:1;overflow:hidden;">
            <div class="chat-time" style="font-size:13px;color:#888;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
            {{ formatSessionTime(chat.createTime) }}
            </div>
            <div class="chat-meta" style="font-size:15px;color:#21ba45;font-weight:bold;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
              <span v-if="chat.grade">{{ chat.grade }}</span>
              <span v-if="chat.knowledgePoint"> | {{ chat.knowledgePoint }}</span>
            </div>
          </div>
          <el-button
            class="chat-delete-x"
            link
            size="small"
            @click.stop="deleteChat(chat.sessionId)"
            style="margin-left: 8px; padding: 0; min-width: 0;"
          >
            <svg viewBox="0 0 16 16" width="16" height="16" style="display:inline-block;"><line x1="4" y1="4" x2="12" y2="12" stroke="#bbb" stroke-width="2" stroke-linecap="round"/><line x1="12" y1="4" x2="4" y2="12" stroke="#bbb" stroke-width="2" stroke-linecap="round"/></svg>
          </el-button>
        </div>
      </div>
      <div class="sidebar-user-bottom">
        <template v-if="userStore.userInfo">
          <el-dropdown trigger="click" @command="handleUserMenu" placement="top-start">
            <div class="user-card" style="cursor:pointer;">
              <div class="user-avatar"
                :style="{ background: userStore.userInfo.avatarColor || '#409EFF' }"
              >
                <el-icon><svg viewBox="0 0 24 24" width="22" height="22"><circle cx="12" cy="8" r="4" fill="#fff"/><rect x="6" y="16" width="12" height="4" rx="2" fill="#fff"/></svg></el-icon>
              </div>
              <span class="user-name">{{ userStore.userInfo.username }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="settings">设置</el-dropdown-item>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template v-else>
          <div class="sidebar-login-btn">
            <el-button type="success" @click="$emit('show-login')">登录</el-button>
          </div>
        </template>
      </div>
    </template>
    <template v-else>
      <el-button type="primary" :icon="Plus" class="new-chat-btn" size="small" circle @click="newChat" />
      <div class="sidebar-user-bottom-collapsed">
        <template v-if="userStore.userInfo">
          <el-dropdown trigger="click" @command="handleUserMenu" placement="right-start">
            <div class="user-avatar user-avatar-collapsed"
              :style="{ background: userStore.userInfo.avatarColor || '#409EFF' }"
              style="cursor:pointer;"
            >
              <el-icon><svg viewBox="0 0 24 24" width="28" height="28"><circle cx="12" cy="8" r="4" fill="#fff"/><rect x="6" y="16" width="12" height="4" rx="2" fill="#fff"/></svg></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="settings">设置</el-dropdown-item>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </div>
    </template>
  </aside>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/store/user'
import { Plus, ArrowDown } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { aiApi } from '@/api/ai'
import { formatSessionTime } from '@/utils/timeFormat'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useChatStore } from '@/store/chat'

const chatList = ref([])
const activeChatId = ref(null)
const collapsed = ref(false)
const toggleCollapse = () => {
  collapsed.value = !collapsed.value
}

const chatStore = useChatStore()

const newChat = async () => {
  // 跳转到欢迎区（不带sessionId）
  router.push({ path: '/' })
  // 重置主页面状态
  window.dispatchEvent(new CustomEvent('reset-chat'))
  // 新建对话后刷新聊天记录栏
  window.dispatchEvent(new CustomEvent('refresh-sidebar-sessions'))
}

const selectChat = (id) => {
  activeChatId.value = id;
  if (activeChatId.value) {
    // 跳转到答题主界面并带上 sessionId
    router.push({ path: '/chat', query: { sessionId: activeChatId.value } });
  } else {
    router.push('/');
  }
};
const userStore = useUserStore()
const defaultAvatar = 'https://cdn.jsdelivr.net/gh/ChatGPTNextWeb/ChatGPT-Next-Web@main/public/avatar/user.png'
const router = useRouter()
const handleLogout = () => {
  userStore.logout()
  window.location.reload()
}
const userMenuVisible = ref(false)

const handleUserMenu = (command) => {
  if(command === 'settings') {
    // 打开设置
    window.dispatchEvent(new CustomEvent('show-settings-dialog'))
  } else if(command === 'theme') {
    // 主题切换，后续可实现
    // window.dispatchEvent(new CustomEvent('show-theme-dialog'))
  } else if(command === 'logout') {
    handleLogout()
  }
}

// 加载会话列表
const loadSessions = async () => {
  if (!userStore.userInfo) return
  const res = await aiApi.getSessions(userStore.userInfo.id)
  if (res && res.code === 200) {
    // 兼容后端返回id/sessionId字段
    chatList.value = (res.data || []).map(item => ({
      ...item,
      sessionId: item.sessionId || item.id
    }))
    // 默认选中第一个（已移除自动跳转）
    if (!activeChatId.value && chatList.value.length > 0) {
      activeChatId.value = chatList.value[0].sessionId
      // 不再自动跳转到 /ai/GenerateQuestion?sessionId=xxx
    }
  }
}

const deleteChat = async (sessionId) => {
  try {
    await ElMessageBox.confirm(
      '删除数据无法恢复，是否确定删除？',
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger',
      }
    )
  } catch {
    // 用户取消
    return
  }
  try {
    // 使用统一封装的 aiApi.deleteSession 方法
    const res = await aiApi.deleteSession(sessionId)
    if (res.code === 200 || res.code === 0) {
      chatList.value = chatList.value.filter(c => c.sessionId !== sessionId)
      ElMessage.success('删除成功')
      // 如果当前删除的是激活的会话，自动切换
      if (activeChatId.value === sessionId) {
        if (chatList.value.length > 0) {
          selectChat(chatList.value[0].sessionId)
        } else {
          activeChatId.value = null
          router.push('/')
        }
      }
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (e) {
    ElMessage.error('删除失败')
  }
}

onMounted(() => {
  loadSessions();
  
  // 监听新对话事件
  const handleNewChatEvent = (e) => {
    if (e.detail && e.detail.new) {
      resetChat();
    }
  };
  window.addEventListener('reset-chat', handleNewChatEvent);

  // 新增：监听刷新聊天记录事件
  const handleRefreshSessions = () => {
    loadSessions();
  };
  window.addEventListener('refresh-sidebar-sessions', handleRefreshSessions);

  // 新增：监听头像颜色更新事件
  const handleAvatarColorUpdate = () => {
    userStore.setUserInfo({ ...userStore.userInfo })
  }
  window.addEventListener('user-avatar-color-updated', handleAvatarColorUpdate)

  // 组件卸载时移除监听
  onUnmounted(() => {
    window.removeEventListener('reset-chat', handleNewChatEvent);
    window.removeEventListener('refresh-sidebar-sessions', handleRefreshSessions);
    window.removeEventListener('user-avatar-color-updated', handleAvatarColorUpdate);
  });
});
</script>

<style scoped>
.sidebar {
  width: 240px;
  background: #f5f5f5;
  border-right: 1px solid #eee;
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 16px 0;
  transition: width 0.2s;
  overflow: hidden;
  position: relative;
}
.sidebar.collapsed {
  width: 60px;
  min-width: 60px;
  padding: 32px 0 16px 0;
}
.logo-bar {
  background: none;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
  height: 77px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0 0 0 0;
  margin-bottom: 0;
}
.logo-bar-collapsed {
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  padding: 0;
  height: auto;
}
.logo {
  font-size: 48px;
  font-weight: 900;
  color: #222;
  text-align: center;
  margin-bottom: 0;
  flex: none;
  font-family: 'Alibaba PuHuiTi', 'Futura', 'Segoe UI', 'PingFang SC', 'Source Han Sans SC', '思源黑体', 'Microsoft YaHei', Arial, sans-serif;
  display: flex;
  align-items: center;
  height: 77px;
  padding-left: 18px;
  letter-spacing: 2px;
}
.sidebar.collapsed .logo {
  display: none;
}
.sidebar.collapsed .new-chat-btn {
  width: 40px;
  height: 40px;
  margin: 0 auto 32px auto;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}
.collapse-btn {
  width: 32px;
  height: 32px;
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  outline: none;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0;
  margin-left: 24px;
}
.sidebar.collapsed .collapse-btn {
  margin: 0 auto 32px auto;
}
.collapse-btn img {
  display: block;
}
.new-chat-btn {
  width: 90%;
  margin: 0 auto 16px auto;
  display: block;
  background: #21ba45 !important;
  color: #fff !important;
  border: none !important;
  transition: background 0.2s;
}
.new-chat-btn:hover,
.new-chat-btn:focus {
  background: #179a36 !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}
.chat-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px;
}
.chat-item {
  padding: 10px 12px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 8px;
  transition: background 0.2s;
}
.chat-item.active, .chat-item:hover {
  background: #eafaf1;
  color: #21ba45;
}
.sidebar-login-btn {
  width: 90%;
  margin: 24px auto 0 auto;
  text-align: center;
}
.sidebar-user-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24px;
}
.sidebar-username {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 8px;
}
.user-card {
  display: flex;
  align-items: center;
  padding: 0;
  margin-bottom: 0;
  background: none;
  box-shadow: none;
  border-radius: 0;
}
.user-avatar {
  width: 36px;
  height: 36px;
  background: #21ba45;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}
.user-icon {
  width: 22px;
  height: 22px;
  display: block;
}
.user-name {
  color: #222;
  font-size: 15px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
html[data-theme='dark'] .sidebar .user-name {
  color: #fff !important;
}
.user-menu-popover {
  background: #232738 !important;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.18);
  color: #fff;
  padding: 0;
}
.user-menu-list {
  padding: 12px 0;
}
.user-menu-header {
  display: flex;
  align-items: center;
  padding: 0 20px 10px 20px;
  border-bottom: 1px solid #33384a;
  margin-bottom: 8px;
}
.user-menu-item {
  padding: 10px 20px;
  cursor: pointer;
  font-size: 16px;
  color: #fff;
  transition: background 0.2s;
}
.user-menu-item:hover {
  background: #2d3144;
}
.user-menu-right {
  float: right;
  color: #aaa;
  font-size: 14px;
}
.user-settings-btn {
  width: 100%;
  text-align: left;
  color: #fff;
  font-size: 15px;
  padding: 8px 0 8px 54px;
  cursor: pointer;
  transition: background 0.2s;
  border-radius: 8px;
  margin-top: 2px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.sidebar.collapsed .user-settings-btn {
  padding: 8px 0 8px 0;
  justify-content: center;
}
.user-settings-btn:hover {
  background: #2d3144;
}
.sidebar-user-bottom {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding-bottom: 24px;
  margin-top: auto;
}
.sidebar-user-bottom-collapsed {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  position: absolute;
  bottom: 24px;
  left: 0;
}
.user-avatar-collapsed {
  width: 40px;
  height: 40px;
  background: #409eff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.large-btn {
  font-size: 17px !important;
  height: 42px !important;
  margin-top: 18px !important;
  color: #fff;
  background: #21ba45;
}
.sidebar-divider {
  width: 70%;
  height: 1.5px;
  background: #e0e0e0;
  border-radius: 1px;
  margin: 28px auto 18px auto;
}
.sidebar-section-title {
  color: #21ba45;
  font-size: 14px;
  text-align: left;
  margin: 8px 0 20px 24px; /* 将下边距由4px改为20px */
  letter-spacing: 1px;
}
:deep(.el-dropdown-menu__item.is-active),
:deep(.el-dropdown-menu__item:hover) {
  color: #222 !important;
  background: #eafaf1 !important;
}
.chat-delete-x {
  background: none !important;
  border: none !important;
  box-shadow: none !important;
  padding: 0 !important;
  min-width: 0 !important;
  margin-left: 8px;
  color: #bbb !important;
  font-size: 16px !important;
  line-height: 1;
  vertical-align: middle;
  transition: color 0.2s;
}
.chat-delete-x:hover svg line {
  stroke: #666;
}
</style>

<style scoped>
.sidebar-login-tip {
  color: #888;
  font-size: 13px;
  margin: 16px 0 12px 24px;
}
</style> 